package com.xwzy.dependencyTools;

import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class Main {
    public static void main(String[] args) throws IOException {
//        String pa= Main.class.getResource("Main.class").getPath()+"result.txt";
        String pa=System.getProperty("user.dir")+"\\result.txt";
        String res;
        if (args.length>0&&args[0].equals("1"))
            res=generate_add_maven();
        else
            res=generate_lib_maven();
        Path path= Paths.get(pa);
        try (BufferedWriter bufferedWriter= Files.newBufferedWriter(path, StandardCharsets.UTF_8)){
            bufferedWriter.write(res);
        }

    }

    public String getPath() {
        String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
        if (System.getProperty("os.name").contains("dows")) {
            path = path.substring(1, path.length());
        }
        if (path.contains("jar")) {
            path = path.substring(0, path.lastIndexOf("."));
            return path.substring(0, path.lastIndexOf("/"));
        }
        return path.replace("target/classes/", "");
    }

    /*
     * @description: 生成本地相关代码maven
     * @author: teer
     * @date: 2022/6/28 21:59
     */
    public static String generate_add_maven(){
        String pa= System.getProperty("user.dir");
//        String pa= Main.class.getResource("Main.class").getPath();
        String path=pa+"\\lib";
        File file=new File(path);
        File[] files=file.listFiles();
        List<String> fileNameList=new ArrayList<>();
        if (files != null) {
            fileNameList= Arrays.stream(files).map(File::getName).collect(Collectors.toList());
        }
        StringBuffer stringBuffer=new StringBuffer();
        fileNameList.stream()
                .map(x->"        <dependency>\n" +
                        "            <groupId>com.xwzy.batch</groupId>\n" +
                        "            <artifactId>batch"+x.substring(0,x.lastIndexOf("."))+"</artifactId>\n" +
                        "            <version>1.0</version>\n" +
                        "            <type>jar</type>\n" +
                        "        </dependency>\n")
                .forEach(stringBuffer::append);
        String res=new String(stringBuffer);
        System.out.println(res);

        StringBuffer stringBuffer1=new StringBuffer();
        fileNameList.stream()
                .map(x->"mvn install:install-file -DgroupId=\"com.xwzy.batch\" -Dfile="+path+"\\"+x.substring(0,x.lastIndexOf("."))+
                        ".jar -DartifactId=\"batch"+x.substring(0,x.lastIndexOf("."))+"\" -Dversion=\"1.0\" -Dpackaging=jar\n")
                .forEach(stringBuffer1::append);
        System.out.println(stringBuffer1);
        stringBuffer1.append("\n").append(stringBuffer);
        return new String(stringBuffer1);
    }


    /*
     * @description: 生成scope=system， maven
     * @author: teer
     * @date: 2022/6/28 21:59
     */
    public static String generate_lib_maven(){
        String pa= System.getProperty("user.dir");
//        String pa= Main.class.getResource("Main.class").getPath();
        String path=pa+"\\lib";
        File file=new File(path);
        File[] files=file.listFiles();
        StringBuffer stringBuffer=new StringBuffer();
        assert files != null;
        Arrays.stream(files)
                .map(x->new JarFile(x).getInfo())
                .forEach(stringBuffer::append);
        String res=new String(stringBuffer);
//        System.out.println(res);
        return res;
    }

    public static class JarFile{
        File file;
        String groupId;
        String artifactId;
        String version;
        public JarFile(File file){
            this.file=file;
        }
        public String getInfo(){
            String res= "";
            try(ZipFile zipFile=new ZipFile(file)) {
                Enumeration<? extends ZipEntry> entries=zipFile.entries();
                while (entries.hasMoreElements()){
                    ZipEntry entry=entries.nextElement();
                    if (entry.getName().endsWith("pom.xml")){
                        boolean hasParent=false;
                        boolean enterParent=false;
                        try(Scanner scanner=new Scanner(zipFile.getInputStream(entry),"US-ASCII")){
                            while (scanner.hasNextLine()){
                                String line=scanner.nextLine();
                                if (line.contains("parent")){
                                    enterParent=!enterParent;
                                    hasParent=true;
                                }else if(line.contains("<groupId>")){
                                    groupId=line;
                                }else if(!enterParent&& line.contains("<artifactId>")){
                                    artifactId=line;
                                }else if(line.contains("<version>")){
                                    version=line;
                                }else if(!hasParent&&groupId!=null&&artifactId!=null&&version!=null){
                                    break;
                                }else if (line.contains("<dependencies")||line.contains("<dependency")||line.contains("<properties")
                                        ||line.contains("<profiles")||line.contains("<name")){
                                    break;
                                }
                            }
                        }
                        if (groupId!=null && artifactId!=null && version!=null){
                            res="<dependency>\n"
                                    +"\t"+groupId.trim()+"\n"
                                    +"\t"+artifactId.trim()+"\n"
                                    +"\t"+version.trim()+"\n"
                                    +"\t<scope>system</scope>\n"
                                    +"\t<systemPath>${pom.basedir}/lib/"+file.getName()+"</systemPath>\n"
                                    + "</dependency>\n";
                        }else {
//                            res=file.getCanonicalPath()+" meiyou pom\n";
                        }
                    }
                }
            }catch (Exception e){
                System.out.println(e);
            }
            return res;
        }
    }
}
